package org.mianshi.ali;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

// cat /home/admin/logs/*.log | grep "Login" | sort | uniq -c | sort -nr   转为java代码实现
public class 日志输出1 {
    public static void main(String[] args) {
        //文件列表
        List<String> filePaths = new ArrayList<>();
        //读取文件
        List<String> logs = new ArrayList<>();
        AtomicInteger threadCount = new AtomicInteger(0);
        filePaths.forEach(filePath -> {
            new Thread(() -> {
                try {
                    handleFile(logs, filePath);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                threadCount.incrementAndGet();
            }).start();
        });
        if (threadCount.getAndIncrement() == filePaths.size()) {
            List<Map.Entry<String, Integer>> entries = handleLog(logs);
            entries.forEach(entry -> {
                System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
            });
        }


    }

    private static List<Map.Entry<String, Integer>> handleLog(List<String> logs) {
        Map<String, Integer> logMap = logs.stream().collect(Collectors.toMap(Function.identity(), log -> 1, Integer::sum));
        return logMap.entrySet().stream().sorted(Comparator.comparing(Map.Entry<String, Integer>::getValue, Comparator.reverseOrder()).thenComparing(Map.Entry::getKey)).collect(Collectors.toList());
    }

    private static void handleFile(List<String> logs, String filePath) throws IOException {
        BufferedReader bf = new BufferedReader(new FileReader(filePath));
        String content = null;
        while ((content = bf.readLine()) != null) {
            if (content.contains("Login")) {
                logs.add(content);
            }
        }
    }
}
